package com.xiang.community.interceptor;

import com.xiang.community.annotation.LoginRequired;
import com.xiang.community.entity.LoginTicket;
import com.xiang.community.entity.User;
import com.xiang.community.service.CommonService;
import com.xiang.community.service.UserService;
import com.xiang.community.utils.CookieUtil;
import com.xiang.community.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Date;

import static com.xiang.community.constant.LoginConstant.MAP_KEY_TOKEN;
import static com.xiang.community.constant.RedisUtilConstant.PREFIX_USER_ID;

/**
 * @author qixiangLi
 * @Date 2021/10/16
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private UserService userService;
    @Resource
    private CommonService commonService;
    @Resource
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);
        if (loginRequired == null) {
            return true;
        }

        // 从cookie中获取凭证
        String token = CookieUtil.getValue(request, MAP_KEY_TOKEN);
        if (token != null) {
            LoginTicket loginTicket = userService.findLoginTicket(token);
            // 检查凭证是否有效
            if (loginTicket != null && loginTicket.getStatus() == 0 && loginTicket.getExpired().after(new Date())) {
                // 根据凭证查询用户
                String currentUserId = redisUtil.getValueFromString(PREFIX_USER_ID, token);
                if (StringUtils.isBlank(currentUserId)) {
                    return false;
                }
                User user = commonService.getUserByUserId(currentUserId);
                // 角色类型不匹配
                if (user != null && loginRequired.roleType() != 0 && loginRequired.roleType() != user.getType()) {
                    return false;
                }

                return true;
            }
        }
        return false;
    }
}
